<template>
  <el-card class="box-card">
    <el-button icon="Plus" type="primary" @click="addTag">添加标签</el-button>
    <el-input
      v-model="keyword"
      placeholder="输入关键词查询相似标签"
      @input="searchSimilarTags"
      style="width: 300px; margin-left: 20px"
    ></el-input>
    <el-table style="margin-top: 10px" border :data="tagArr">
      <el-table-column
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="标签名称" align="center">
        <template #="{ row, $index }">
          <pre>{{ row.name }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="热度指数" align="center">
        <template #="{ row, $index }">
          <el-progress
            :text-inside="true"
            :stroke-width="20"
            :percentage="customPercentageMethod(row.heat)"
            :color="customColorMethod(row.heat)"
          >
            <span>{{ row.heat }}</span>
          </el-progress>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="default"
            icon="Edit"
            @click="(event: MouseEvent) => updateTag(row)"
          ></el-button>
          <el-popconfirm
            :title="`您确定要删除 ${row.name} 吗?`"
            width="200px"
            icon="Delete"
            @confirm="removeTag(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="default" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    对话框组件：在添加标签与修改已有标签的业务时候使用结构-->
    <!--    v-model:属性用户控制对话框的显示与隐藏  -->
    <!--    title:设置对话框左上角标题  -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="tagParams.id ? '修改标签' : '添加标签'"
      @keydown.enter="confirm"
    >
      <el-form
        style="width: 80%"
        :model="tagParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item
          label="标签名称"
          label-width="90px"
          label-position="left"
          prop="name"
        >
          <el-input
            placeholder="请您输入标签名称"
            v-model="tagParams.name"
          ></el-input>
        </el-form-item>
      </el-form>
      <!--      具名插槽-->
      <template #footer>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
        <el-button type="danger" size="default" @click="cancel">取消</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTag,
  reqAddTag,
  reqUpdateTag,
  reqDeleteTag,
  reqSimilarTags,
} from '@/api/tag'
import type { Tag, TagRecords, TagResponseData } from '@/api/tag/type'

let dialogFormVisible = ref<boolean>(false)
//存储已有标签的数据
let tagArr = ref<TagRecords>([])
//获取el-form组件实例
let formRef = ref()

let tagParams = reactive<Tag>({
  name: '',
})

let keyword = ref<string>('')

//获取已有标签的接口封装为一个函数，在任何情况下获取数据，调用此函数即可
const getHasTag = async () => {
  let result: TagResponseData = await reqHasTag()
  if (result.code == 200) {
    tagArr.value = result.data
  }
  console.log(result)
}
//组件挂载完毕钩子———发送一次请求，获取第一页、一页三个已有标签数据
onMounted(() => {
  getHasTag()
})

const addTag = async () => {
  tagParams.id = undefined
  tagParams.name = ''

  dialogFormVisible.value = true

  nextTick(() => {
    formRef.value.clearValidate('name')
  })
}

const customPercentageMethod = (heat: number) => {
  if (heat <= 100) {
    return heat
  }
  if (heat >= 100) {
    return 100
  }
}

//控制热度条颜色变化
const customColorMethod = (percentage: number) => {
  if (percentage < 10) {
    return 'blue'
  }
  if (percentage < 50) {
    return 'green'
  }
  if (percentage < 100) {
    return 'orange'
  }
  if (percentage > 100) {
    return 'red'
  }
}

//注入了一个参数row
//row：即为当前行对应的标签
const updateTag = (row: Tag) => {
  //清空校验规则的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('name')
  })
  //对话框显示
  dialogFormVisible.value = true
  //ES6语法合并对象
  Object.assign(tagParams, row)
  console.log(tagParams)
}

//标签名称校验自定义方法
const validatorName = (rule: any, value: any, callback: any) => {
  //当表单元素触发blur的时候，会触发此方法
  //自定义校验规则
  if (value.length >= 2) {
    //校验通过
    callback()
  } else {
    //校验未通过返回的错误信息
    callback(new Error('标签名称大于等于两位'))
  }
}

//表单校验规则对象
const rules = {
  name: [
    //required代表这个字段是必须校验的，表现为表单项前面出现一个五角星
    //trigger表示触发校验时机[blur：失去焦点时，change：表单发生变化时]
    { required: true, trigger: 'blur', validator: validatorName },
  ],
}

//气泡确认框确定按钮的回调
const removeTag = async (id: number) => {
  let result: any = await reqDeleteTag(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '标签删除成功',
    })
    //删除成功之后立马再次获取已有标签数
    await getHasTag()
  } else {
    ElMessage({
      type: 'error',
      message: '删除标签失败',
    })
  }
}

const confirm = async () => {
  // 在发请求之前，要对整个表单进行校验,这里回触发写好的该表单内的所有校验函数
  const isValid = await formRef.value.validate()
  if (!isValid) return // 如果校验失败，直接返回

  try {
    let result: any
    if (tagParams.id) {
      result = await reqUpdateTag(tagParams)
    } else {
      result = await reqAddTag(tagParams)
    }
    console.log(result)
    if (result && result.code == 200) {
      // 关闭对话框
      dialogFormVisible.value = false
      // 弹出提示信息
      ElMessage({
        type: 'success',
        message: tagParams.id ? '修改标签成功' : '添加标签成功',
      })
      // 更新页面信息
      getHasTag()
    } else {
      // 添加标签失败
      ElMessage({
        type: 'error',
        message: tagParams.id ? '修改标签失败' : '添加标签失败',
      })
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage({
      type: 'error',
      message: '请求失败，请稍后再试',
    })
  }
}
//对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}

// 相似查询
const searchSimilarTags = async () => {
  if (keyword.value) {
    let result: TagResponseData = await reqSimilarTags(keyword.value)
    if (result.code == 200) {
      tagArr.value = result.data
    } else {
      ElMessage({
        type: 'error',
        message: '相似查询失败',
      })
    }
  } else {
    getHasTag()
  }
}
</script>

<style scoped lang="scss"></style>
